
//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by 孙明海 on 16/1/26.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import Foundation

class UserAccountViewModel {
    //单例
    static let sharedUserAccount = UserAccountViewModel()
    
    //token 
    var accessToken: String? {
        return account?.access_token
    }
    
    //用户模型
    var account: UserAccount?
    
    var accountPath: String {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        return (path as NSString).stringByAppendingPathComponent("userAccount.plist")
    }
    //用户登录标记
    var userLogin: Bool {
        return account?.access_token != nil && !isExpired
    }
    
    // 图像url
    var avatarURL: NSURL {
        return NSURL(string: (account?.avatar_large) ?? "")!
    }
    
    //判断账户是否 过期
    private var isExpired: Bool {
        if account?.expiresDate?.compare(NSDate()) != .OrderedDescending {
            return true
        }
        return false
    }
    private init() {
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        if isExpired {
            account = nil
            print("已经过期")
        }
        print(account)
    }
}

//MARK: - 用户网络相关方法
extension UserAccountViewModel {
    func loadAccountToken(code: String, finished: (isSuccessed: Bool) -> ()) {
        NetworkTools.sharedNetworkTools.loadAccountToken(code) { (result, error) -> (Void) in
            if error != nil {
                print(error)
                finished(isSuccessed: false)
                return
            }
            self.account = UserAccount(dict: (result as! [String: AnyObject]))
            
            self.loadUserInfo(self.account!, finished: finished)
        }
    }
    private func loadUserInfo(account: UserAccount, finished: (isSuccessed: Bool) -> ()) {

        NetworkTools.sharedNetworkTools.loadUserInfo(account.uid!) { (result, error) -> (Void) in
            if error != nil {
                print(error)
                finished(isSuccessed: false)
                return
            }
            
            guard let dict = result as? [String: AnyObject] else {
                print("格式错误")
                finished(isSuccessed: false)
                return
            }
            
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
            print(self.accountPath)
            finished(isSuccessed: true)
        }
    }
}